package rabbitmq.rpc;

import com.rabbitmq.client.*;
import rabbitmq.constants.Constants;
import rabbitmq.utils.WorkUtils;

import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeoutException;

public class Client {
    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
        ConnectionFactory factory = WorkUtils.createConnectionFactory();
        //建立连接
        Connection connection = factory.newConnection();
        //开启信道
        Channel channel = connection.createChannel();
        //声明队列
        channel.queueDeclare(Constants.RPC_QUEUE1,true,false,false,null);
        channel.queueDeclare(Constants.RPC_QUEUE2,true,false,false,null);
        //发送消息
        /**
         * 消息中需要包含replyTo和correlationId两种属性
         * replyTo: 客户端发送的目标队列
         * correlationId: 匹配相应的标识
         */
        String correlationId = UUID.randomUUID().toString();
        AMQP.BasicProperties basicProperties = new AMQP.BasicProperties().builder()
                        .replyTo(Constants.RPC_QUEUE1)
                        .correlationId(correlationId)
                        .build();
        String msg = "hello RPC ~";
        channel.basicPublish("", Constants.RPC_QUEUE1, basicProperties, msg.getBytes());
        //接收消息
        /**
         * 接收消息是异步的，所以需要使用阻塞队列进行阻塞，防止接收不到消息
         */
        BlockingQueue<String> blockingQueue = new ArrayBlockingQueue<>(4);
        Consumer consumer = new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag,
                                       Envelope envelope,
                                       AMQP.BasicProperties properties,
                                       byte[] body)
            {
                String ret = new String(body);
                System.out.println("接收到消息：" + ret);
                String cID = properties.getCorrelationId();
                if (cID.equals(correlationId)){
                    blockingQueue.add(ret);
                }
            }
        };
        channel.basicConsume(Constants.RPC_QUEUE2, true, consumer);
        String result = blockingQueue.take();
        System.out.println("RPC [Client 响应结果]：" + result);
    }
}
